package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwt;
import jakarta.annotation.Resource;
import org.example.bean.login.User;
import org.example.config.JwtConfig;
import org.example.mapper.AthMapper;
import org.example.service.AthService;
import org.example.util.JsonResult;
import org.example.util.MD5Util;
import org.example.util.ResultTool;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Auther:Liu
 * @Testname:AthServiceImpl
 * @Date:2025/8/13 17:58
 */
@Service
public class AthServiceImpl extends ServiceImpl<AthMapper, User>implements AthService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;


//    public JsonResult Login(User user) {
//        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        wrapper.eq("username", user.getUsername());
//        User one = getOne(wrapper);
//        if (one == null) {
//            return ResultTool.fail(201,"账号不存在");
//        }
//        if (!one.getPassword().equals(MD5Util.encryptMD5(user.getPassword()))) {
//            return ResultTool.fail(202,"密码错误");
//        }
//        String jwtToken = JwtConfig.getJwtToken(one);
//        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
//        ops.set("token"+one.getId(), jwtToken);
//        return ResultTool.success(jwtToken);
//    }

    @Override
    public JsonResult isLogin(String token) {
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            return ResultTool.fail(203,"用户没有登陆");
        }
        Claims claims = JwtConfig.parseJWT(token);
        Object userId = claims.get("id");
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String s = ops.get("token" + userId);
        if (s == null) {
            return ResultTool.fail(203,"用户没有登陆");
        }
        if (!Objects.equals(s,token)){
            return ResultTool.fail(203,"用户没有登陆");
        }
        return ResultTool.success(claims.get("name"));
    }

    @Override
    public JsonResult Loginout(String token) {
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            return ResultTool.fail(204,"推出失败");
        }
        Claims claims = JwtConfig.parseJWT(token);
        Object userId = claims.get("id");
        Boolean deleted = stringRedisTemplate.delete("token" + userId);
        if (!deleted) {
            return ResultTool.fail(204,"推出失败");
        }
        return ResultTool.success("success");
    }
}
